/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2021-01-05
*/
package com.rzico.article.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.article.entity.Article;
import com.rzico.article.entity.ArticleReview;
import com.rzico.article.service.ArticleReviewService;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 笔记评论控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2021-01-05
 */
@Api(description = "笔记评论接口")
@RestController
@RequestMapping("/articleReview")
public class ArticleReviewController extends BaseController {

    @Autowired
    private ArticleReviewService articleReviewService;

    /**
     * 分页查询笔记评论
     *
     * @return
    */
    @ApiOperation("分页查询笔记评论")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query")
    })
    public CommResult<ArticleReview> list(Date startDate, Date endDate,Long articleId, Pageable pageable) {

        Map<String, Object> params = null;
        //Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        if (articleId == null || articleId <= 0) {
            return CommResult.success();
        }
        params = new HashMap<>();
        params.put("articleId", articleId);
        List<ArticleReview> all = articleReviewService.selectList(params);
        //PageResult<ArticleReview> pageResult = new PageResult<ArticleReview>(all, startPage.getTotal(), pageable);
        //List<ArticleReview> RList = pageResult.getData();
        List<ArticleReview> RList = all;
        Map<Long, ArticleReview> allmap = new HashMap<>();
        Map<Long, ArticleReview> headMap = new HashMap<>();
        List<ArticleReview> result = new ArrayList<>();
        for (ArticleReview c : RList) {
            if (c.getForReviewId() == null || c.getForReviewId() == 0) {
                //头评论
                headMap.put(c.getId(), c);
            }
            allmap.put(c.getId(), c);
        }
        //遍历查出的全部评论
        for (ArticleReview c : RList) {
            //如果这个评论不是最顶评论
            if(c.getParentId() != null && c.getParentId() > 0) {
                //查出这个评论的最顶评论
                ArticleReview parent = headMap.get(c.getParentId());
                //查出他所回复的评论
                ArticleReview reviewfor = allmap.get(c.getForReviewId());
                //如果最顶评论没被删掉 和 自己回复的评论被删掉 下一条处理
                if (parent == null || reviewfor == null) {
                    continue;
                }
                //如果最顶评论List<> child为空,创建一个List<> child
                if (parent.getChild() == null) {
                    parent.setChild(new ArrayList<>());
                }
                //把子孙放入List<> child
                if(c.getParentId() != null && c.getForReviewId() != null && c.getParentId() >=0 && c.getForReviewId() >= 0 && c.getParentId() != c.getForReviewId())
                c.setReviewName(reviewfor.getNickname());
                parent.getChild().add(c);
            }
        }

        result = headMap.values().stream().sorted(ArticleReview::compareTo)
                //.filter(x -> !"".equalsIgnoreCase(x))
                .collect(Collectors.toList());
        Map map = new HashMap();
        map.put("data", result);
        map.put("size",all.size());
        return CommResult.success(map);
       // map.entrySet().stream().map(et ->et.getKey()+"_"+et.getValue()).collect(Collectors.toList());
//        for (ArticleReview c : RList) {
//            if (c.getForReviewId() != null && c.getForReviewId() != 0) {
//                ArticleReview parent = map.get(c.getForReviewId());
//                if (parent == null) {
//                    continue;
//                }
//                if (parent.getChild() == null) {
//                    parent.setChild(new ArrayList<>());
//                }
//
//                parent.getChild().add(c);
//            }
//        }
    }

    /**
     * 查询单条笔记评论
     *
     * @return
    */
    @ApiOperation("查询单条笔记评论")
    @GetMapping("/find/{id}")
    public CommResult<ArticleReview> find(@PathVariable String id) {
        ArticleReview result = articleReviewService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("articleReview",result);
        return CommResult.success(data);

    }

    /**
     * 保存笔记评论
     *
     * @param articleReview
     * @return
     */
    @ApiOperation("保存笔记评论")
    @PostMapping("/save")
    public CommResult<ArticleReview> save(@RequestBody ArticleReview articleReview) {

        int affectCount = articleReviewService.insert(articleReview);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        ArticleReview result = articleReviewService.findById(articleReview.getId());
        return CommResult.success(result);
    }


//    @ApiOperation("保存笔记评论")
//    @PostMapping("/save")
//    public CommResult<ArticleReview> save(@RequestBody ArticleReview articleReview) {
//        long be = System.currentTimeMillis();
//        articleReview.setAvatar("1");
//        articleReview.setParentId(2L);
//        articleReview.setForReviewId(5L);
//        articleReview.setContent("我是一颗棉花树,我是一个棉花树啊,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树," +
//                "我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树," +
//                "我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,我是一颗棉花树,");
//        articleReview.setCreateDate(new Date());
//        articleReview.setMemberId(2255L);
//        articleReview.setNickname("棉花树");
//        for (long i = 2500;i < 2700; i++) {
//            articleReview.setArticleId(i);
//            int affectCount = articleReviewService.insert(articleReview);
//        }
//        for (long i = 2600;i < 2800; i++) {
//            articleReview.setArticleId(i);
//            int affectCount = articleReviewService.insert(articleReview);
//        }
//        for (long i = 100;i < 500; i++) {
//            articleReview.setArticleId(i);
//            int affectCount = articleReviewService.insert(articleReview);
//        }
//        for (long i = 4000;i < 4500; i++) {
//            articleReview.setArticleId(i);
//            int affectCount = articleReviewService.insert(articleReview);
//        }
////        if (affectCount <= 0) {
////            return CommResult.error();
////        }
////        ArticleReview result = articleReviewService.findById(articleReview.getId());
//        //return CommResult.success(result);
//        long end = System.currentTimeMillis();
//        return CommResult.success("完毕:"+ (end -be));
//    }

    /*
     * 批量删除笔记评论
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除笔记评论", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除笔记评论,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<ArticleReview> del(@PathVariable String ids) {

        articleReviewService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新笔记评论
     *
     * @param articleReview
     * @return
     */
    @Log(desc = "更新笔记评论", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新笔记评论")
    @PostMapping("/update")
    public CommResult<ArticleReview> update(@RequestBody ArticleReview articleReview) {
        int affectCount = articleReviewService.updateByPrimaryKeySelective(articleReview);
        if (affectCount <= 0){
            return CommResult.error();
        }
        ArticleReview result = articleReviewService.findById(articleReview.getId());
        return CommResult.success(result);
    }

}
